<?php

namespace App\Http\Controllers\Sms;

use App\Http\Controllers\Controller;
use App\Services\Cache\CacheServicesProvider;
use App\Services\Core\Traits\Response;
use App\Services\Ext\Sms\SmsServicesProvider;
use Illuminate\Http\Request;

class Ali extends Controller
{
    use Response;

    private $smsServiceProvider;

    public function __construct()
    {
        $this->smsServiceProvider = new SmsServicesProvider();
    }

    public function code(Request $request)
    {
        if (false == preg_match('/^1[3456789][0-9]{9}$/', $request->post('mobile'))) {
            $this->fail('手机号不正确');
        }

        $conf    = config('ali.sms');
        $service = $this->smsServiceProvider->ali->client([
            'accessKeyId'     => $conf['accessKeyId'],
            'accessKeySecret' => $conf['accessKeySecret'],
            'templateCode'    => $conf['template']['register']['templateCode'],
            'signName'        => $conf['template']['register']['signName'],
        ]);

        $code = $service->send($request->post('mobile'), mt_rand(1000, 9999));

        if ($code) {
            (new CacheServicesProvider())->sms->setCode($request->post('mobile'), $code);
            return $this->success(msg: '短信已发送');
        }

        $this->fail('短信发送失败');
    }
}
